<template>
  <!--: 数据量过大，过滤改为后端实现 filter-option="filterOption"  option-filter-prop="children"-->
  <a-select
    show-search
    :placeholder="$t(placeholder)"
    @search="getData"
    :allow-clear="clear"
    :mode="mode"
    :disabled="disabled"
    :filterOption="false"
    :maxTagCount="maxTagCount"
    v-model="selectedValue"
    @blur="handlerBlur"
    @focus="getData"
    :loading="loading"
    :getPopupContainer="getPopupContainerWrapper"
  >
    <a-select-option v-for="item in modelOptions" :key="item.id" :value="item.id" :title="item.name">
      {{ item.name }}
    </a-select-option>
  </a-select>
</template>
<script>
// 所有车型列表
import CommonSelect from '@/components/SelfComponents/CommonSelect.vue'
import modelApi from '@/api/modules/system/modelMana'
import lodash from 'lodash'
export default {
  components: {
    CommonSelect
  },
  props: {
    getPopupContainer: {
      type: Function,
      default: undefined
    },
    mode: {
      type: String,
      default: 'default'
    },
    defaultValue: {
      type: [String, Array, Object, undefined],
      default () {
        return undefined
      }
    },
    query: {
      type: Object,
      default () {
        return null
      }
    },
    hasAll: {
      type: Boolean,
      default: true
    },
    maxTagCount: {
      type: Number,
      default: 1
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clear: {
      type: Boolean,
      default: false
    },
    concatTrimLevel: {
      type: Boolean,
      default: true
    },
    selectFirstOption: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '车型'
    }
  },
  model: {
    prop: "defaultValue", //绑定的值，通过父组件传递
    event: "change" //自定义事件名
  },
  computed: {
    selectedValue:{
      get() {
        return this.defaultValue;
      },
      set(val) {
        this.$emit('change', val);    // 触发
        this.changeOption(val)
      }
    }
  },
  data () {
    return {
      modelOptions: [],
      loading: false,
      selectFirstTimeDone: false,
      havenotSelectFirst: true,
      isManualReset: false,
      selectValue: undefined,
    }
  },
  watch: {
    'query': {
      handler () {
        // this.getData()
      },
      immediate: true
    },
    // defaultValue: {
    //   handler (val) {
    //     if (val !== this.selectedValue) {
    //       this.selectedValue = this.defaultValue
    //     }
    //   },
    //   immediate: true
    // },
    async selectedValue (val) {
      if (!val) {
        // this.getData();
      } else {
        // let data = await this.handleSelected(this.modelOptions);
        // data &&  this.modelOptions.splice(0, 0, ...data);
      }
    }
  },
  async created () {
    //方法定义上设置的话是共用的，多实例时相互影响
    this.getData = lodash.debounce(this.getData, 500);
    // this.getData();
    if (this.selectedValue && this.modelOptions.length === 0) {
      // this.getData();
      let data = await this.handleSelected(this.modelOptions);
      data &&  this.modelOptions.splice(0, 0, ...data);
    }
  },
  methods: {
    handlerBlur () {
      if (this.selectedValue!=='' && !this.selectedValue) {
        this.$emit('change', this.selectValue);
      }
    },
    getPopupContainerWrapper (triggerNode) {
      if (this.getPopupContainer) {
        return this.getPopupContainer(triggerNode);
      }
      if (!this.appendToBody && triggerNode) {
        return triggerNode.parentNode
      } else {
        return window.document.body
      }
    },
    transData(data) {
      if (!data) {
        return [];
      }
      data = data.map(item => {
        let name = item.code
        name += (item.name ? '[' + item.name + ']' : '')
        if (this.concatTrimLevel && item.trimLevel !== '默认款型') {
          name += (item.trimLevel ? '[' + item.trimLevel + ']' : '')
        }
        // 加code与trimLevel是为了有些地方选择的时候需要这两个参数
        return {
          id: item.id,
          name,
          modelName: item.name,
          code: item.code,
          trimLevel: item.trimLevel,
          title: item.name
        }
      });
      return data;
    },
    async handleSelected(data) {
      if (Array.prototype.isPrototypeOf(this.selectedValue) && this.selectedValue.length === 0) {
        return [];
      }
      //选中项不存在则单独搜索选中项追加至下拉框
      if (this.selectedValue) {
        let exist = data.filter(item => {
          if (this.selectedValue instanceof Array) {
            return this.selectedValue.includes(item.id);
          } else {
            return this.selectedValue === item.id;
          }
        });
        if (exist && exist.length > 0) {
          return [];
        }
        let ids = [];
        if (this.selectedValue instanceof Array) {
          ids = this.selectedValue;
        } else {
          ids = [this.selectedValue];
        }
        let res = await modelApi.getMyAllModel({...this.query, ids})
        return this.transData(res.data);
        // this.modelOptions.splice(0, 0, ...data);
      } else {
        return [];
      }
    },
    getData(value){
      this.selectValue = value
      value = Array.isArray(value) ? '': value
      this.loading = true;
        modelApi.getMyAllModel({...this.query,searchWord: value}).then(async (res) => {
          let data = this.transData(res.data)
          let selectedData = await this.handleSelected(data);
          selectedData && data.splice(0, 0, ...selectedData);
          this.modelOptions = this.hasAll ? [
            {
              id: '',
              name: this.$t('all')
            }
          ].concat(data) : data
          const lengthNotEmpty = (Array.isArray(data) && data.length > 0);
          if (lengthNotEmpty && this.selectFirstOption) {
            this.selectedValue = this.modelOptions[0].id
            this.selectFirstTimeDone = true
          }
        }).finally(() => this.loading = false)
      },
    // },
    changeOption (val) {
      let item = this.modelOptions.find(e => e.id === val);
      this.$emit('changeoption', val, item)
      if (this.isManualReset) {
        this.isManualReset = false
      }
      // 对于流量统计页面来说，需要默认选中第一个选中，且都导出的时候需要拿到车型的名称等数据
      // 所以根据selectFirstOption的属性来判断时候往上传递id对应的车型
      if (this.selectFirstOption) {
        const selectedModelObj = this.modelOptions.find((item) => {
          return item.id === val
        })
        this.$emit('transSelecetdModelObj', selectedModelObj)
        if (this.selectFirstTimeDone && this.havenotSelectFirst) {
          this.$emit('selectFirstTimeDone')
          this.havenotSelectFirst = false
        }
      }
    },
    // 因为要默认选中第一个车型的原因，所以当重置搜索条件时，需要由父组件调用此方法，恢复到第一个选项
    recoverToFirstOption () {
      if (this.modelOptions.length > 0) {
        this.isManualReset = true
        this.selectedValue = this.modelOptions[0].id
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  }
}
</script>
